//
//  HRZPlaceholderTextView.m
//  EMarket
//
//  Created by 石头 on 2018/5/16.
//  Copyright © 2018年 好日子. All rights reserved.
//

#import "HRZPlaceholderTextView.h"
#import "UIView+SPExtension.h"

@interface HRZPlaceholderTextView()

/* 占位文字label */
@property (strong , nonatomic)UILabel *placeholderLabel;

@end

@implementation HRZPlaceholderTextView

- (UILabel *)placeholderLabel{
    if (!_placeholderLabel) {
        _placeholderLabel = [[UILabel alloc] init];
        _placeholderLabel.numberOfLines = 0;
        [self addSubview:_placeholderLabel];
        
        _placeholderLabel.sp_x = 4;
        _placeholderLabel.sp_y = 7;
        
    }
    return _placeholderLabel;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        /** 弹簧效果-垂直 */
        self.alwaysBounceVertical = YES;
        
        self.font = [UIFont systemFontOfSize:16];
        
        self.placeholderColor = [UIColor lightGrayColor];
        
        /** 监听文字变化 */
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];
        
    }
    return self;
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor {
    _placeholderColor = placeholderColor;
    self.placeholderLabel.textColor = _placeholderColor;
}

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = [placeholder copy];
    
    self.placeholderLabel.text = _placeholder;
    [self updatePlaceholderLabelSize];
}

- (void)setFont:(UIFont *)font {
    [super setFont:font];
    self.placeholderLabel.font = font;
}

- (void)setText:(NSString *)text {
    [super setText:text];
    [self textDidChange];
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    [super setAttributedText:attributedText];
    [self textDidChange];
}

/** 监听文字变化 */
- (void)textDidChange {
    /** 占位文字是否显示 */
    self.placeholderLabel.hidden = self.hasText;
}

/** 更新文字尺寸 */
- (void)updatePlaceholderLabelSize {
    CGSize maxSize = CGSizeMake(kScreenWidth - 2 *self.placeholderLabel.sp_x, MAXFLOAT);
    
    self.placeholderLabel.sp_size = [_placeholder boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.font} context:nil].size;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.placeholderLabel.sp_width = self.sp_width - 2 * self.placeholderLabel.sp_x;
    
    [self.placeholderLabel sizeToFit];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
